package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    private StringRedisTemplate stringRedisTemplate;
    private final static long BEGIN_TIMESTAMP = 1672531200L;
    private final static int COUNT_BITS = 32;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix) {
        //.1生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long toEpochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = toEpochSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //3、自增长
        Long decrement = stringRedisTemplate.opsForValue().decrement("icr" + keyPrefix + ":" + date);
        return timeStamp << COUNT_BITS | decrement;
    }

}
